package org.jeecg.modules.appuser.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.appuser.constant.PayTypeConstant;
import org.jeecg.modules.appuser.entity.*;
import org.jeecg.modules.appuser.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.mall.entity.TbMnUser;
import org.jeecg.modules.mall.service.ITbMnUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 用户体现审核表
 * @Author: jeecg-boot
 * @Date: 2020-05-18
 * @Version: V1.0
 */
@Api(tags = "用户体现审核表")
@RestController
@RequestMapping("/appuser/tbUserCash")
@Slf4j
public class TbUserCashController extends JeecgController<TbUserCash, ITbUserCashService> {
    @Autowired
    private ITbUserCashService tbUserCashService;

    @Autowired
    private ITbUserWalletService tbUserWalletService;

    @Autowired
    private ITbUserWalletDetailService tbUserWalletDetailService;


    @Autowired
    private ITbUserAlipayService tbUserAlipayService;

    @Autowired
    private ITbUserNoticeService tbUserNoticeService;
    @Autowired
    private ITbMnUserService tbMnUserService;
    /**
     * 分页列表查询
     *
     * @param tbUserCash
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "用户体现审核表-分页列表查询")
    @ApiOperation(value = "用户体现审核表-分页列表查询", notes = "用户体现审核表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(TbUserCash tbUserCash,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<TbUserCash> queryWrapper = QueryGenerator.initQueryWrapper(tbUserCash, req.getParameterMap());
        Page<TbUserCash> page = new Page<TbUserCash>(pageNo, pageSize);
        IPage<TbUserCash> pageList = tbUserCashService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param tbUserCash
     * @return
     */
    @AutoLog(value = "用户体现审核表-添加")
    @ApiOperation(value = "用户体现审核表-添加", notes = "用户体现审核表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody TbUserCash tbUserCash) {
        tbUserCash.setApplyState(3);
        tbUserCashService.save(tbUserCash);
        return Result.ok("添加成功！");
    }


    /**
     * 添加
     *
     * @param tbUserCash
     * @return
     */
    @AutoLog(value = "审核")
    @ApiOperation(value = "审核", notes = "审核")
    @PostMapping(value = "/applyStatus")
    public Result<?> applyStatus(@RequestBody TbUserCash tbUserCash) {
        if (tbUserCash.getApplyState()==1) {
            //审核通过，则开始提现
            TbUserCash oldTbUserCash = tbUserCashService.getById(tbUserCash.getId());
            BigDecimal cashBalance = oldTbUserCash.getCashBalance();
            TbUserWallet tbUserWallet = tbUserWalletService.getOneByUser_id(oldTbUserCash.getUserId());
            TbUserAlipay tbUserAlipay= tbUserAlipayService.getByUserId(oldTbUserCash.getUserId());
            if(null==tbUserAlipay){
                return Result.error("没有绑定支付宝");
            }
            synchronized (tbUserWallet) {
                BigDecimal balance = tbUserWallet.getBalance();
                if (balance.compareTo(cashBalance) >= 0) {
                    BigDecimal newBalance = balance.subtract(cashBalance);
                    tbUserWallet.setBalance(newBalance);
                    tbUserWalletService.updateById(tbUserWallet);
                    TbUserWalletDetail tbUserWalletDetail = new TbUserWalletDetail();
                    tbUserWalletDetail.setUserId(oldTbUserCash.getUserId());
                    tbUserWalletDetail.setWalletId(tbUserWallet.getId());
                    tbUserWalletDetail.setPayFrom(PayTypeConstant.PAYFORM_CASH);
                    tbUserWalletDetail.setPayNumber(cashBalance);
                    tbUserWalletDetail.setPayType(PayTypeConstant.PAYTYPE_EXPEND);
                    tbUserWalletDetail.setBalance(newBalance);
                    if (tbUserWalletDetailService.save(tbUserWalletDetail)) {
                        addMsgNotice(tbUserWalletDetail,oldTbUserCash.getUserId());

                        log.info("提现审批完成");
                    }
                } else {
                    return Result.error("资金不足");
                }
            }
        } else {
            tbUserCash.setApplyState(0);
        }
        tbUserCashService.updateById(tbUserCash);
        return Result.ok("审核完成！");
    }
    //增加消息通知
    private void addMsgNotice(TbUserWalletDetail tbUserWalletDetail, String user_id) {
        TbUserNotice tbUserNotice=new TbUserNotice();
        TbMnUser tbMnUser= tbMnUserService.getById(user_id);
        tbUserNotice.setNoticeContent(tbMnUser.getPhone()+"提现完成,提现金额是:"+ tbUserWalletDetail.getPayNumber());
        tbUserNotice.setNoticeTitle(DateUtil.now() + ":提现完成");
        tbUserNotice.setNoticeSendStatus("0");
        tbUserNotice.setUserId(user_id);
        tbUserNotice.setNoticeType("1");
        tbUserNoticeService.addUserNotice(tbUserNotice);
    }

    /**
     * 编辑
     *
     * @param tbUserCash
     * @return
     */
    @AutoLog(value = "用户体现审核表-编辑")
    @ApiOperation(value = "用户体现审核表-编辑", notes = "用户体现审核表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody TbUserCash tbUserCash) {
        tbUserCashService.updateById(tbUserCash);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "用户体现审核表-通过id删除")
    @ApiOperation(value = "用户体现审核表-通过id删除", notes = "用户体现审核表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        tbUserCashService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "用户体现审核表-批量删除")
    @ApiOperation(value = "用户体现审核表-批量删除", notes = "用户体现审核表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.tbUserCashService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "用户体现审核表-通过id查询")
    @ApiOperation(value = "用户体现审核表-通过id查询", notes = "用户体现审核表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        TbUserCash tbUserCash = tbUserCashService.getById(id);
        if (tbUserCash == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(tbUserCash);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param tbUserCash
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TbUserCash tbUserCash) {
        return super.exportXls(request, tbUserCash, TbUserCash.class, "用户体现审核表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, TbUserCash.class);
    }

}
